package com.teama4.shop.interceptor;

import com.teama4.shop.annotation.NeedLogin;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @Description 登录拦截
 * @Param
 */

@Component
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①:START 方法注解级拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        NeedLogin methodAnnotation = method.getAnnotation(NeedLogin.class);
        // 有 @LoginRequired 注解，需要认证
        if (methodAnnotation != null) {
            if (null == request.getSession().getAttribute("userId")) {
                String scheme = request.getScheme();//http
                String serverName = request.getServerName(); //localhost
                int serverPort = request.getServerPort();//8180
                String servletPath = request.getRequestURI();// /...
                String queryString = request.getQueryString();// ?...
                String url = scheme + "://" + serverName + ":" + serverPort + servletPath;
                String servletPathAndqueryString = servletPath;
                if (queryString != null) {
                    url += "?" + queryString;
                    servletPathAndqueryString +="?" + queryString;
                }

                request.setAttribute("toUrl", servletPathAndqueryString);
                request.setAttribute("needLogin","true");
                request.getRequestDispatcher("/login").forward(request, response);
//                System.out.println("该方法需要登录，请登录");
                return false;
            } else {
                return true;
            }


        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

